// pages/index/category.js
import { getSellersByCategory } from '../../utils/apis'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    page: 0,
    size: 20,
    list: null,
    hasMore: true,
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.id = options.id || 1
    this.siteId = options.siteId
    wx.setNavigationBarTitle({
      title: options.name
    })
    this.loadData()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.setData({
      page: 0,
      list: null,
      hasMore: true,
      loading: false
    })
    this.loadData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var { loading, hasMore } = this.data
    if (hasMore && !loading) {
      this.loadData()
    }
  },

  loadData() {
    var that = this
    var { id: category_id, siteId: siteId } = this

    var { loading, page, size } = this.data
    if (loading) {
      return
    }
    that.setData({
      loading: true
    })

    getSellersByCategory({
      category_id,
      siteId,
      page,
      size
    })
      .then(result => {
        var { list } = that.data
        wx.stopPullDownRefresh()
        that.setData({
          loading: false,
          list: list ? list.concat(result.stores) : result.stores,
          hasMore: result.count > (that.data.page + 1) * 20,
          page: page + 1
        })

        console.log(result)
      })
      .catch(err => {
        console.log(err)
      })
  }
})
